import express from 'express';
import { User, Favorite, Cashgift, Checkin, Order } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { checkPermission, aesEncrypt } from '../../utils/utils'; // 工具类

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  // User.Modal.sync();
  // 权限校验
  let userInfo = {}
  await checkPermission(Request, Response, minLevel).then(res => {
    // 获取用户表内容
    userInfo = res
  })
  await getFavoriteNumber(userInfo.id, Response).then(res => {
    // 获取用户收藏数
    userInfo.favoriteNumber = res
  })
  await getCashgiftNumber(userInfo.id, Response).then(res => {
    // 获取用户淘礼金数
    userInfo.cashgiftNumber = res
  })
  await getOrderNumber(userInfo.id, Response).then(res => {
    // 获取用户订单数
    userInfo.orderNumber = res
  })
  await hasCheckIn(userInfo.id, Response).then(res => {
    // 判断用户是否签到
    userInfo.hasCheckIn = res
  })
  // !!!!!!过滤关键字段
  delete userInfo.password
  delete userInfo.unionId
  Response.json({
    data: userInfo,
  })
});

function getFavoriteNumber(userId, Response) {
  return new Promise((resolve, reject) => {
    Favorite.Modal.count({
      where: {
        userId: userId,
      }
    }).then(res => {
      resolve(res)
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

function getCashgiftNumber(userId, Response) {
  return new Promise((resolve, reject) => {
    Cashgift.Modal.count({
      where: {
        userId: userId,
      }
    }).then(res => {
      resolve(res)
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

function getOrderNumber(userId, Response) {
  return new Promise((resolve, reject) => {
    Order.Modal.count({
      where: {
        userId: userId,
      }
    }).then(res => {
      resolve(res)
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

function hasCheckIn(userId, Response) {
  return new Promise((resolve, reject) => {
    Checkin.Modal.findAll({
      where: {
        userId: userId,
      },
      raw: true, // 返回标准json格式
    }).then(res => {
      if (res && res.length > 0) {
        //已经签到过
        resolve(true)
      } else {
        resolve(false)
      }
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

module.exports = router;